
// import { listChartByPageUsingPOST } from '@/services/ant-design-pro/chartController';
// import { message, Avatar, List, Card, Result } from 'antd';
// import React from 'react';
// import { useEffect, useState } from 'react';
// import ReactECharts from 'echarts-for-react';
// import { useModel } from 'umi';
// import { Input } from 'antd';

// const { Search } = Input;


// const MyChart: React.FC = () => {

//   const initParams = {
//     current: 1,
//     pageSize: 10,
//     sortField: 'createTime',
//     sortOrder: 'desc'
//   }
//   const {initialState} = useModel('@@initialState')
//   const {currentUser} = initialState ?? {}
//   const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>({...initParams})
//   const [chartList, setChartList] = useState<API.Chart[]>()
//   const [ total, setTotal] = useState<number>(0)
//   const [loading, setLoading] = useState<boolean>(true)

//   const loadData = async () => {
//     setLoading(true)
//     try {
//       const res = await listChartByPageUsingPOST(searchParams);
//       if(res?.data){
        
//         setTotal(res.data?.total ?? 0)
//         // 隐藏图表的title
//         if(res.data?.records){
//           // 处理表头
//           res.data.records.forEach(data => {
//             const chartOption = JSON.parse(data.genChart?? '{}')
//             chartOption.title = undefined
//             data.genChart = JSON.stringify(chartOption)
//           })
//           setChartList(res.data?.records ?? [])
//         }
//       }else{
//         throw new Error("加载数据失败")
//       }
//     } catch (e: any) {
//       message.error('获取我的图表失败' + e.message)
//     }
//     setLoading(false)
    
//   }

//   useEffect(() => {
//     loadData();
//   }, [searchParams])

//   return (
//     <div className='my-chart-page'>
//       <div style={{marginBottom: 16, width: '50%'}}>
//         <Search placeholder="请输入内容" loading={loading} enterButton onSearch={(value) => {
//           setSearchParams({
//             ...initParams,
//             name: value,
//           })
//         }} />
//       </div>
    
//       <List
//         itemLayout="vertical"
//         pagination={{
//           onChange: (page, pageSize) => {
//             setSearchParams({
//               ...searchParams,
//               current: page,
//               pageSize,
//             })
//           },
//           current: searchParams.current,
//           pageSize: 4,
//           total: total
//         }}
//         grid={{
//           gutter: 16,
//           xs: 1,
//           sm: 1,
//           md: 1,
//           lg: 1,
//           xl: 2,
//           xxl: 2,
//         }}
//         loading={loading}
//         dataSource={chartList}
      
//         renderItem={(item) => (
//           <List.Item
//             key={item.id}
//           >
//             <Card style={{width: '100%', height: '650px'}}>
//               <List.Item.Meta
//                 avatar={<Avatar src={currentUser?.userAvatar} />}
//                 title={item.name}
//                 description={item.chartType ? '图表类型:' + item.chartType : undefined}
//               />
//               <>
//                 {
//                   item.status === 'wait' && <> 
//                     <Result 
//                       // 状态为警告
//                       status={'warning'}
//                       title='待生成'
//                       subTitle={item.execMessage ?? '当前图表生成繁忙，请耐心等待'}
//                     />
//                   </>
//                 }
//                 {
//                   item.status === 'running' && <> 
//                     <Result 
//                       // 状态为警告
//                       status={'info'}
//                       title='图表生成中'
//                       subTitle={item.execMessage}
//                     />
//                   </>
//                 }
//                 {
//                   item.status === 'succeed' && <> 
//                     <div>
//                     <div>
//                       <h3><b>分析目标: {item.goal}</b></h3>
//                     </div>
//                     <div>
//                       { <ReactECharts option={item.genChart && JSON.parse(item.genChart ?? '')} />}
//                     </div>
//                     <div>
//                       <h3><b>分析结论</b></h3>
//                       {item.genResult}
//                     </div>
//                     </div>
//                   </>
//                 }
//                 {
//                   item.status === 'failed' && <> 
//                     <Result 
//                       // 状态为警告
//                       status={'error'}
//                       title='图表生成失败'
//                       subTitle={item.execMessage}
//                     />
//                   </>
//                 }
//               </>
              
              
//             </Card>
//           </List.Item>
//         )}
//       />
//     </div>
//   )
// };
// export default MyChart;
import { listChartByPageUsingPOST } from '@/services/ant-design-pro/chartController';
import { message, Avatar, List, Card, Result, Button } from 'antd';
import React from 'react';
import { useEffect, useState } from 'react';
import ReactECharts from 'echarts-for-react';
import { useModel } from 'umi';
import { Input } from 'antd';
import { SyncOutlined } from '@ant-design/icons';

const { Search } = Input;

const MyChart: React.FC = () => {
  const initParams = {
    current: 1,
    pageSize: 10,
    sortField: 'createTime',
    sortOrder: 'desc'
  };

  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};
  const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>(() => {
    try {
      const storedParams = localStorage.getItem('chartSearchParams');
      return storedParams ? JSON.parse(storedParams) : { ...initParams };
    } catch (error) {
      console.error('Error parsing chartSearchParams from localStorage:', error);
      return { ...initParams };
    }
  });
  const [chartList, setChartList] = useState<API.Chart[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(true);

  const loadData = async () => {
    setLoading(true);
    try {
      const res = await listChartByPageUsingPOST(searchParams);
      if (res?.data) {
        const { records, total: dataTotal } = res.data;
        setTotal(dataTotal ?? 0);
        // 隐藏图表的title
        if (records) {
          const updatedChartList = records.map(data => {
            const chartOption = JSON.parse(data.genChart ?? '{}');
            chartOption.title = undefined;
            data.genChart = JSON.stringify(chartOption);
            return data;
          });
          setChartList(updatedChartList);
        }
      } else {
        throw new Error("加载数据失败");
      }
    } catch (e: any) {
      message.error('获取我的图表失败' + e.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [searchParams]);

  useEffect(() => {
    try {
      localStorage.setItem('chartSearchParams', JSON.stringify(searchParams));
    } catch (error) {
      console.error('Error storing chartSearchParams to localStorage:', error);
      // 在本地存储不可用的情况下，可以采取其他策略，例如使用内存变量来保存参数
      // 这里直接将参数设置为初始值
      setSearchParams({ ...initParams });
    }
  }, [searchParams]);

  const handlePageChange = (page: number, pageSize?: number) => {
    setSearchParams(prevParams => ({
      ...prevParams,
      current: page,
      pageSize: pageSize ?? prevParams.pageSize,
    }));
  };

  const fetchData = () => {
    setLoading(true);
    
    setTimeout(() => {
      loadData();
      setLoading(false);
    }, 1000); // 模拟刷新操作，2秒后更新数据
  };

  return (
    <div className='my-chart-page'>
      <div style={{ marginBottom: 16, width: '50%', display: 'flex' }}>
        <Search
          placeholder="请输入内容"
          loading={loading}
          enterButton
          onSearch={(value) => {
            setSearchParams({
              ...initParams,
              name: value,
            });
          }}
        />
        <div>
          <Button 
            type="primary" 
            onClick={fetchData} 
            loading={loading} 
            icon={<SyncOutlined 
            spin={loading} />} >
            刷新
          </Button>
        </div>
      </div>

      <List
        itemLayout="vertical"
        pagination={{
          onChange: handlePageChange,
          current: searchParams.current,
          pageSize: searchParams.pageSize,
          total: total
        }}
        grid={{
          gutter: 16,
          xs: 1,
          sm: 1,
          md: 1,
          lg: 1,
          xl: 2,
          xxl: 2,
        }}
        loading={loading}
        dataSource={chartList}
        renderItem={(item) => (
          <List.Item key={item.id}>
            <Card style={{ width: '100%', height: '650px' }}>
              <List.Item.Meta
                avatar={<Avatar src={currentUser?.userAvatar} />}
                title={item.name}
                description={item.chartType ? '图表类型:' + item.chartType : undefined}
              />
              <>
                {item.status === 'wait' && (
                  <Result
                    status={'warning'}
                    title='待生成'
                    subTitle={item.execMessage ?? '当前图表生成繁忙，请耐心等待'}
                  />
                )}
                {item.status === 'running' && (
                  <Result
                    status={'info'}
                    title='图表生成中'
                    subTitle={item.execMessage}
                  />
                )}
                {item.status === 'succeed' && (
                  <div>
                    <div>
                      <h3><b>分析目标: {item.goal}</b></h3>
                    </div>
                    <div>
                      <ReactECharts option={item.genChart && JSON.parse(item.genChart ?? '')} />
                    </div>
                    <div>
                      <h3><b>分析结论</b></h3>
                      {item.genResult}
                    </div>
                  </div>
                )}
                {item.status === 'failed' && (
                  <Result
                    status={'error'}
                    title='图表生成失败'
                    subTitle={item.execMessage}
                  />
                )}
              </>
            </Card>
          </List.Item>
        )}
      />
    </div>
  );
};

export default MyChart;
